
Page({
  data: {
    goodsInfo:{}
  },
  onLoad: function (options) {
    const goods_id = options.goods_id;
    this.getGoodsDetails(goods_id)
    .then((data)=>{
      this.setData({goodsInfo:{
        goods_id:data.goods_id,
        goods_name:data.goods_name,
        goods_price:data.goods_price,
        pics:data.pics,
        goods_introduce:data.goods_introduce
      }})
    })
  },
  // 获取商品信息
  getGoodsDetails(goods_id){
    wx.showLoading({
      title: '加载中',
      mask:true
    });
    return new Promise((resolve,reject)=>{
      wx.request({
        url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/detail",
        data:{goods_id},
        success:(res)=>{
          resolve(res.data.message)
          wx.hideLoading();
        }
      })
    })
  },
  ImgClick(e){
    const currentUrl = e.currentTarget.dataset.url;
    const urls = this.data.goodsInfo.pics.map((item)=>item.pics_mid);
    wx.previewImage({
      current:currentUrl,
      urls: urls,
    })
  },
  // 加入购物车
  addCart(){
    let cart = wx.getStorageSync("cart") || [];
    let index = cart.findIndex(item=>item.goods_id === this.data.goodsInfo.goods_id);
    if (index === -1) {
      this.data.goodsInfo.num = 1;
      this.data.goodsInfo.checked = false;
      cart.push(this.data.goodsInfo);
    }else{
      cart[index].num += 1;
    }
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      mask: true, /* 防止疯狂点击 */
    });
  }
})